package pers.jg.rrsserver.controller

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper
import com.google.gson.GsonBuilder
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.web.bind.annotation.*
import pers.jg.rrsserver.entity.Policy
import pers.jg.rrsserver.mapper.PolicyMapper

@RestController
@CrossOrigin
class PolicyController {

    val dateFormat = "yyyy-MM-dd'T'HH:mm:sssZ"

    class PolicyList {
        lateinit var policyList: ArrayList<Policy>
    }

    @Autowired
    private lateinit var policyMapper: PolicyMapper

    @PostMapping("/api/postNewPolicy")
    fun postNewPolicy(
        @RequestBody data: String
    ): String {

        val gson = GsonBuilder()
            .setDateFormat(dateFormat)
            .create()
        val newPolicy = gson.fromJson(data, Policy::class.java)
        println(newPolicy.id)
        val res = policyMapper.insert(newPolicy)
        return res.toString()

    }

    @GetMapping("/api/getPolicyList")
    fun getPolicyList(
        @RequestParam(value = "key", defaultValue = "") key: String,
        @RequestParam(value = "orderBy", defaultValue = "") orderBy: String
    ): String {
        val queryWrapper = QueryWrapper<Policy>()
        if (key != "") {
            queryWrapper.like("title", key).or().like("content", key)
        }
        if(orderBy == ""){
            queryWrapper.orderByDesc("post_time")   // 按照时间降序排序
        }
        else{
            queryWrapper.orderByDesc(orderBy)   // 按照给定的字段降序排序
        }
        val policyList = policyMapper.selectList(queryWrapper)
        val gson = GsonBuilder()
            .create()
        return gson.toJson(policyList)
    }


    @PostMapping("/api/updatePolicy")
    fun updatePolicy(
        @RequestBody data: String
    ): String {

        val gson = GsonBuilder()
            .setDateFormat(dateFormat)
            .create()
        val policy = gson.fromJson(data, Policy::class.java)
        println(policy.id)
        val res = policyMapper.updateById(policy)
        return res.toString()
    }

    @PostMapping("/api/deletePolicy")
    fun deletePolicy(
        @RequestParam("id") id: String
    ): String {
        println(id)
        return policyMapper.deleteById(id).toString()
    }

    @GetMapping("/api/getPolicy")
    fun getPolicy(
        @RequestParam("id") id: String
    ): String {
        val policy = policyMapper.selectById(id)
        val gson = GsonBuilder()
            .create()
        return gson.toJson(policy)
    }

    @PostMapping("/api/policyPageviewAdd1")
    fun policyPageviewAdd1(
        @RequestParam("id") id: String
    ): String {
        val policy = policyMapper.selectById(id)
        policy.pageview = policy.pageview!! + 1
        policyMapper.updateById(policy)
        val gson = GsonBuilder()
            .create()
        return gson.toJson(policy)
    }
}